# coding: utf8
# try something like
import datetime
now = datetime.datetime.now()
from makan import *

def call():
    session.forget()
    return service()

def test():
    from xmlrpclib import ServerProxy
  #  s = ServerProxy('http://127.0.0.1:8000/makan/checkin/call/xmlrpc')
    s = ServerProxy('http://www.e-makan.com/welcome/checkin/call/xmlrpc')
    p = s.xAddCheckin(1, 16)
    
    return  dict(p = p)

#TODO: make adding checkins by using place id instead of lat and long
def coreAddCheckin( pid , uid ):
    added = []
    chk = []
    uchk = []
  
   #note that place is one row
    q = db.places.id == pid
    q1 = db.users.id  == uid
     
    #retrieve checkins for this place
    place_checkins =  db(q).select(db.places.checkins).first()
    #retrieve checkins for this user
    user_checkins = db(q1).select(db.users.checkins).first()
#insert checkin and return the new row id
    if not place_checkins.checkins== None : 
        for p in place_checkins.checkins :
            chk.append(p)

    if not user_checkins.checkins== None : 
        for p in user_checkins.checkins :
            uchk.append(p)    
            
    checkinId =   db.checkins.insert(user =  uid , place = pid  ,datetime = now )
    chk.append(checkinId)
    uchk.append(checkinId)
 # place_checkins.append(checkinId)  
    uadded =  db(db.users.id == uid ).update( checkins =  uchk)
    added  =  db(db.places.id == pid ).update( checkins =  chk )
    if added :
        if uadded :
            msg = "Added"
    else:
        msg= "Error"       
    return msg 


@service.xmlrpc
def xAddCheckin(pid, uid ):
     return coreAddCheckin(pid, uid )

@auth.requires_login()
def addCheckin():
      if request.post_vars:
        vars = request.post_vars
        uid = vars.uid
        long= float(vars.long)
        lat= float(vars.lat)    
       
        return coreAddCheckin(  pid , uid  )
